<template>
  <view class="record-sheet-components" v-show="show">
    <!-- 录音面板 -->
    <view class="at-action-sheet__overlay" style="opacity:1" />
    <view class="record-sheet">
      <image :lazy-load="true" v-show="recordInInit" @tap="handleRecord('start')" class="record-sheet__start" :src="imageData.START_RECORDER_ICON" />
      <image :lazy-load="true" v-show="recordInStart" @tap="handleRecord('stop')" class="record-sheet__end" :src="imageData.END_RECORDER_ICON" />
      <view class="record-sheet__info">
        <view class="record-sheet__info-wrap">
          <view class="record-sheet__info--status"></view>
          <text class="record-sheet__info--time">{{ recordTime }}''/{{ MAX_RECORD_TIME }}''</text>
        </view>
        <text class="record-sheet__info--text">单击{{recordInStart ? '完成' : '录制'}}</text>
      </view>
      <view @tap="handleRecord('stop','cancel')" class="record-sheet__cancel">
        <view class="record-sheet__cancel--btn">取消</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import Taro from "@tarojs/taro";
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import ActionSheet from "@/components/action-sheet/index.vue";
import { START_RECORDER_ICON, END_RECORDER_ICON } from "@/config/clock-in";
interface ImageData {
  [props: string]: string;
}
/* 最大录音时长 */
const MAX_RECORD_TIME: number = 10 /* min */ * 60;
/* 设置微信录音最大时长 */
const WECHAT_MAX_RECORD_TIME: number = MAX_RECORD_TIME * 1000;
/* 录音初始化状态 */
const RECORD_INIT: number = 0;
/* 录音开始状态 */
const RECORD_START: number = 1;
/* 录音结束状态 */
const RECORD_END: number = 2;
@Component({
  components: { ActionSheet },
})
export default class RecordSheet extends Vue {
  /* 图片对象 */
  imageData: ImageData = {
    /* 录音开始按钮 */
    START_RECORDER_ICON,
    /* 录音结束按钮 */
    END_RECORDER_ICON,
  };
  /* 录音实例 */
  recorderManager = null;
  /* 单次定时器对象 */
  recordTimer: NodeJS.Timer | null = null;
  /* 最大录音时长 单位：s */
  MAX_RECORD_TIME: number = MAX_RECORD_TIME;
  /* 是否保存此次录音-- 在点击取消时不保存 */
  canSaveRecord: boolean = true;
  /* 录制时间 */
  recordTime: number = 0;
  /* 录音状态 */
  /* 0初始化状态 1开始 2停止 */
  recordStatus: number = RECORD_INIT;
  /* 录音loading状态 */
  recordLoading: boolean = false;

  @Prop({ default: false }) show: boolean;
  @Prop({ default: false }) stopRecordSheet: boolean;
  @Watch("stopRecordSheet")
  onstopRecordSheetChange(n) {
    n && this.handleRecord("stop", "cancel");
  }
  /* 录音处在初始化阶段 */
  get recordInInit() {
    return this.recordStatus === RECORD_INIT;
  }
  /* 录音处在开始状态 */
  get recordInStart() {
    return this.recordStatus === RECORD_START;
  }
  /* 录音处在结束状态 */
  get recordInEnd() {
    return this.recordStatus === RECORD_END;
  }

  created() {
    if (this.recorderManager) return;
    this.recorderManager = Taro.getRecorderManager();
    /* 录音开始 */
    this.recorderManager.onStart(() => {
      this.recordLoading = false;
      /* 录音时屏幕常亮 */
      Taro.setKeepScreenOn({
        keepScreenOn: true,
      });
      this.recordTimer = setInterval(() => {
        if (this.recordTime === MAX_RECORD_TIME) {
          this.clearTimer();
          return;
        }
        this.recordTime++;
      }, 1000);
      this.recordStatus = RECORD_START;
    });
    /* 录音结束 */
    this.recorderManager.onStop((res) => {
      /* 录音完成取消屏幕常亮 */
      Taro.setKeepScreenOn({
        keepScreenOn: false,
      });
      this.recordStatus = RECORD_INIT;
      this.$emit("update:show", false);
      this.clearTimer();
      /* 最小录音时间处理 */
      if (Math.ceil(res.duration) < 1000) {
        Taro.showToast({ title: "录制时间不能短于1s!", icon: "none" });
      } else if (!this.canSaveRecord) {
        /* 点击取消时不做保存操作 并重置状态 */
        this.canSaveRecord = true;
      } else {
        this.$emit("recordEnd", res);
      }
      /* 防止快速点击 */
      setTimeout(() => {
        this.recordLoading = false;
      }, 500);
    });
    /**
     * 录音被打断 - 以下场景会触发此事件：微信语音聊天、微信视频聊天。
     */
    this.recorderManager.onInterruptionBegin((res) => {
      this.recorderManager.stop();
    });
    /* 录音错误 */
    this.recorderManager.onError((res) => {
      this.recordLoading = false;
      /* Taro.showToast({
        title: "录音失败，请检查录音设备" + res.errMsg,
        icon: "none",
      }); */
    });
  }

  /* 清除定时器 */
  clearTimer() {
    clearInterval(this.recordTimer);
    this.recordTimer = null;
    /* 计时清空 */
    this.recordTime = 0;
  }

  /* 关闭面板 */
  closeModal() {
    console.log(123);
    this.$emit("update:show", false);
    /* 关闭面板时结束录音 */
    this.recordTime && this.recorderManager.stop();
  }
  /* 录音相关操作 */
  handleRecord(handle: string, canSaveRecord?: string) {
    if (this.recordLoading) return;
    this.recordLoading = true;
    /* 点击取消且未开始录音关闭弹窗 */
    if (handle === "stop" && !this.recordInStart) {
      this.$emit("update:show", false);
      this.recordLoading = false;
      return;
    }
    /* 点击取消改变canSaveRecord（可以保存录音状态） */
    canSaveRecord === "cancel" && (this.canSaveRecord = false);
    this.recorderManager[handle] &&
      this.recorderManager[handle]({
        duration: WECHAT_MAX_RECORD_TIME,
        format: "mp3",
      });
  }
}
</script>

<style lang="scss">
@import "@/assets/scss/tools.scss";
@import "@/assets/scss/theme.scss";
.record-sheet-components {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 20;
  transition: all 1s;
}
.record-sheet {
  @include normal-flex;
  color: $text-color-primary;
  font-size: 28px;
  padding: 0 64px;
  height: 248px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  border-radius: 16px 16px 0px 0px;
  transition: all 1s;
  &__start,
  &__end {
    width: 136px;
    height: 136px;
  }

  &__info {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 48px;
    &-wrap {
      @include normal-flex(flex-start);
    }
    &--status {
      width: 12px;
      height: 12px;
      background: #f56f5e;
      border-radius: 50%;
      margin-right: 12px;
    }
    &--text {
      margin-top: 24px;
      color: $text-color-secondary;
    }
  }
  &__cancel {
    @include normal-flex(flex-end);
    &--btn {
      width: 110px;
      height: 110px;
      background: #ffffff;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.1);
      border-radius: 50%;
      @include normal-flex;
    }
  }
}
</style>